package org.jinyan.wechat.service;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpException;
import org.jinyan.db.dao.IDBDao;
import org.jinyan.db.dao.impl.DBDao;
import org.jinyan.utils.RemoteServiceUtil;
import org.jinyan.wechat.model.WeatherInfo;

public class WeatherService {

	public WeatherInfo getWeather(String area) {
		WeatherInfo info = null;
		String cityCode = "11";
		try {
			cityCode = this.getCityCode(area);
		} catch (SQLException e1) {
			System.out.println("获取城市编码失败" + e1.getLocalizedMessage());
			e1.printStackTrace();
			return info;
		}
		if (cityCode != null) {
			String weatherUrl = "http://www.weather.com.cn/data/cityinfo/"
					+ cityCode + ".html";
			try {
				Map result = RemoteServiceUtil
						.doHttpGetMethod(weatherUrl, null);
				info = mapTOVo(result);
			} catch (HttpException e) {
				System.out.println("获取城市天气失败" + e.getLocalizedMessage());
				e.printStackTrace();
				return info;
			} catch (IOException e) {
				System.out.println("获取城市天气失败" + e.getLocalizedMessage());
				e.printStackTrace();
				return info;
			}
		}

		return info;
	}

	public String getCityCode(String area) throws SQLException {
		System.out.println("获取城市编码" + area);
		String cityCode = null;
		String sql = "select * from weathercode w where w.cityName= ?";
		IDBDao dbDao = new DBDao();
		List list = dbDao.selectList(sql, new Object[] { area });
		if (!list.isEmpty()) {
			Map item = (Map) list.get(0);
			cityCode = (String) item.get("CITYCODE");
		}
		return cityCode;
	}

	private WeatherInfo mapTOVo(Map result) {
		WeatherInfo info = null;
		if (result.containsKey("weatherinfo")) {
			info = new WeatherInfo();
			Map<String, String> item = (Map) result.get("weatherinfo");
			info.setCity(item.get("city"));
			info.setCityid(item.get("cityid"));
			info.setTemp1(item.get("temp1"));
			info.setTemp2(item.get("temp2"));
			info.setWeather(item.get("weather"));
			info.setImg1(item.get("img1"));
			info.setImg2(item.get("img2"));
			info.setPtime(item.get("ptime"));
		}
		return info;

	}
}
